<template>
  <a-table
    rowKey="id"
    size="middle"
    bordered
    :loading="loading"
    :columns="columns"
    :dataSource="tableDataWithTotal"
    :pagination="false"
  >
    <template slot="htmlSlot" slot-scope="text">
      <div v-html="text"></div>
    </template>

    <template slot="imgSlot" slot-scope="text,record">
      <div style="font-size: 12px;font-style: italic;">
        <span v-if="!text">无图片</span>
        <img v-else :src="getImgView(text)" :preview="record.id" alt="" style="max-width:80px;height:25px;"/>
      </div>
    </template>

    <template slot="fileSlot" slot-scope="text">
      <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
      <a-button
        v-else
        ghost
        type="primary"
        icon="download"
        size="small"
        @click="downloadFile(text)"
      >
        <span>下载</span>
      </a-button>
    </template>
  </a-table>
</template>

<script>
import { getAction } from '@api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'

export default {
  name: 'CwTxrygzjbxmxbSubTable',
  mixins: [JeecgListMixin],
  props: {
    record: {
      type: Object,
      default: null,
    }
  },
  data() {
    return {
      description: '退休人员工资及保险明细表内嵌列表',
      disableMixinCreated: true,
      loading: false,
      dataSource: [],
      // 所有需要计算合计的字段（dataIndex集合，共28个）
      totalFields: [
        'retirementPay', 'shf', 'zjshf', 'zjylj', 'zj', 'zjb', 'zengjia', 'zengjiabaoxu',
        'dszv', 'txshf', 'bt', 'jf', 'allowance', 'hardshipAllowance', 'wsf', 'lmryjt',
        'tgjf', 'yzgz', 'zftzbt', 'zzys', 'nyfhj', 'ylbxjs', 'ylbx', 'ylbxde',
        'ylbxjsn', 'cgyb', 'heatingFee', 'yjsbffzg','yyfhj'
      ],
      columns: [
        {
          title: '姓名',
          align: 'center',
          dataIndex: 'name',
        },
        {
          title: '年度',
          align: 'center',
          dataIndex: 'year'
        },
        {
          title: '单位',
          align: 'center',
          dataIndex: 'unit_dictText'
        },
        {
          title: '职务（职称）',
          align: 'center',
          dataIndex: 'zc',
        },
        {
          title: '基本离 退休费',
          align: 'center',
          dataIndex: 'retirementPay',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '2006年前增加 生活费',
          align: 'center',
          dataIndex: 'shf',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '2006年后增加 生活费',
          align: 'center',
          dataIndex: 'zjshf',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '2021年增加养老金',
          align: 'center',
          dataIndex: 'zjylj',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '2022年增加养老金',
          align: 'center',
          dataIndex: 'zj',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '2023年增加养老金',
          align: 'center',
          dataIndex: 'zjb',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '2024年增加养老金',
          align: 'center',
          dataIndex: 'zengjia',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '2025年增加养老金',
          align: 'center',
          dataIndex: 'zengjiabaoxu',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '独生子女加发5%',
          align: 'center',
          dataIndex: 'dszv',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '退休生活补贴',
          align: 'center',
          dataIndex: 'txshf',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '加发5% 补贴',
          align: 'center',
          dataIndex: 'bt',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '教龄满30年加发',
          align: 'center',
          dataIndex: 'jf',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '特殊岗位津贴',
          align: 'center',
          dataIndex: 'allowance',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '艰苦津贴',
          align: 'center',
          dataIndex: 'hardshipAllowance',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '卫生费',
          align: 'center',
          dataIndex: 'wsf',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '劳模荣誉津贴',
          align: 'center',
          dataIndex: 'lmryjt',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '特供加发',
          align: 'center',
          dataIndex: 'tgjf',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '预计涨工资',
          align: 'center',
          dataIndex: 'yzgz',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '住房提租 补贴',
          align: 'center',
          dataIndex: 'zftzbt',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '月应发合计',
          align: 'center',
          dataIndex: 'yyfhj',
          customRender: (text) => this.formatNumber(text, 0) // 整数格式化
        },
        {
          title: '在职月数',
          align: 'center',
          dataIndex: 'zzys',
          customRender: (text) => this.formatNumber(text, 0) // 整数格式化
        },
        {
          title: '年应发合计',
          align: 'center',
          dataIndex: 'nyfhj',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '养老保险基数（年）',
          align: 'center',
          dataIndex: 'ylbxjs',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '养老保险（72%）',
          align: 'center',
          dataIndex: 'ylbx',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '医疗保险（大额）',
          align: 'center',
          dataIndex: 'ylbxde',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '医疗保险基数（年）',
          align: 'center',
          dataIndex: 'ylbxjsn',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '参公医保(5%)',
          align: 'center',
          dataIndex: 'cgyb',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '取暖费',
          align: 'center',
          dataIndex: 'heatingFee',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '预计社保返还资金',
          align: 'center',
          dataIndex: 'yjsbffzg',
          customRender: (text) => this.formatNumber(text)
        },
      ],
      url: {
        listByMainId: '/cw/cwTxrygzjbxmxbTj/queryCwTxrygzjbxmxbByMainId',
      },
    }
  },
  computed: {
    // 带合计行的完整数据
    tableDataWithTotal() {
      if (!this.dataSource || this.dataSource.length === 0) return []

      // 深拷贝原始数据，避免污染
      const newData = JSON.parse(JSON.stringify(this.dataSource))
      // 计算所有字段合计
      const fieldTotals = this.calcAllFieldTotals()

      // 构建合计行
      const totalRow = {
        id: 'total_' + new Date().getTime(), // 唯一ID
        name: '合计',
        year: '',
        unit_dictText: '',
        zc: '',
        // 填充所有合计字段值
        retirementPay: fieldTotals.retirementPay,
        shf: fieldTotals.shf,
        zjshf: fieldTotals.zjshf,
        zjylj: fieldTotals.zjylj,
        zj: fieldTotals.zj,
        zjb: fieldTotals.zjb,
        zengjia: fieldTotals.zengjia,
        zengjiabaoxu: fieldTotals.zengjiabaoxu,
        dszv: fieldTotals.dszv,
        txshf: fieldTotals.txshf,
        bt: fieldTotals.bt,
        jf: fieldTotals.jf,
        allowance: fieldTotals.allowance,
        hardshipAllowance: fieldTotals.hardshipAllowance,
        wsf: fieldTotals.wsf,
        lmryjt: fieldTotals.lmryjt,
        tgjf: fieldTotals.tgjf,
        yzgz: fieldTotals.yzgz,
        zftzbt: fieldTotals.zftzbt,
        zzys: fieldTotals.zzys,
        nyfhj: fieldTotals.nyfhj,
        ylbxjs: fieldTotals.ylbxjs,
        ylbx: fieldTotals.ylbx,
        ylbxde: fieldTotals.ylbxde,
        ylbxjsn: fieldTotals.ylbxjsn,
        cgyb: fieldTotals.cgyb,
        heatingFee: fieldTotals.heatingFee,
        yjsbffzg: fieldTotals.yjsbffzg,
        yyfhj: fieldTotals.yyfhj,
      }

      newData.push(totalRow)
      return newData
    }
  },
  watch: {
    record: {
      immediate: true,
      handler() {
        if (this.record) {
          this.loadData(this.record)
        }
      }
    }
  },
  methods: {
    loadData(record) {
      this.loading = true
      this.dataSource = []
      getAction(this.url.listByMainId, { id: record.id })
        .then((res) => {
          if (res.success) {
            this.dataSource = res.result.records || []
          }
        })
        .finally(() => {
          this.loading = false
        })
    },

    /**
     * 数字格式化通用方法
     * @param text 原始值
     * @param decimal 小数位数（默认2位，在职月数用0位）
     */
    formatNumber(text, decimal = 2) {
      const num = Number(text)
      return isNaN(num) ? '0' + (decimal > 0 ? '.' + '0'.repeat(decimal) : '') : num.toFixed(decimal)
    },

    /**
     * 计算所有字段的合计
     */
    calcAllFieldTotals() {
      // 初始化所有合计字段为0
      const totals = this.totalFields.reduce((obj, field) => {
        obj[field] = 0
        return obj
      }, {})

      // 遍历数据累加
      this.dataSource.forEach(item => {
        this.totalFields.forEach(field => {
          const val = Number(item[field])
          totals[field] += isNaN(val) ? 0 : val
        })
      })

      // 格式化合计结果（在职月数保留0位小数，其他保留2位）
      this.totalFields.forEach(field => {
        const decimal = field === 'zzys' ? 0 : 2
        totals[field] = totals[field].toFixed(decimal)
      })

      return totals
    },

    // 空实现方法，避免报错
    downloadFile(text) {
    },
    getImgView(text) {
      return text
    }
  },
}
</script>

<style scoped>
/* 合计行样式优化，适配多列表格 */
::v-deep .ant-table-tbody tr:last-child {
  background-color: #f0f8fb !important;
}

::v-deep .ant-table-tbody tr:last-child td {
  font-weight: 600 !important;
  border-top: 2px solid #40a9ff !important;
  color: #1890ff !important;
  text-align: center !important;
  white-space: nowrap !important;
}

/* 表格横向滚动优化，避免列挤压 */
::v-deep .ant-table {
  overflow-x: auto !important;
  min-width: 1200px !important;
}

::v-deep .ant-table-column-title {
  white-space: nowrap !important;
}
</style>